//
//  PrinterConnectViewController.swift
//  imember_printer
//
//  Created by feibi on 2022/1/16.
//

import UIKit
import PrinterSDK

private enum CellIndex: Int {
    case connected = 0
    case history = 1
    case scanned = 2
}

class PrinterConnectViewController: BaseViewController {
    // MARK: Property
    private var isScanningWiFi: Bool = false
    private var connectedPrinters = [PTPrinter]()
    private var historyPrinters = [PTPrinter]()
    private var scannedPrinters = [PTPrinter]()
    
    // MARK: - LifeCycle
    override func viewDidLoad() {
        super.viewDidLoad()
        /// 斷開連結時的回調
        PTDispatcher.share().whenUnconnect { [weak self] _, _ in
            self?.checkConnectedPrinter()
            self?.scanPrinters()
        }
        
        /// 檢測檢測設備連接狀態
        checkConnectedPrinter()
        
        /// 掃描設備
        scanPrinters()
    }
    
    // MARK: - Private_M
    override func configUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(goBack))
        
        view.addSubview(tableView)
    }
    
    @objc private func goBack() {
        dismiss(animated: true)
    }
    
    /// 刷新數據
    private func reloadData() {
        historyPrinters = UserDefaultsManager.printers
        /// 過濾掉當前連接的設備
        if !connectedPrinters.isEmpty {
            let connectedPrinter = connectedPrinters.first
            historyPrinters = historyPrinters.filter() { $0.ip != connectedPrinter?.ip }
            scannedPrinters = scannedPrinters.filter() { $0.ip != connectedPrinter?.ip }
        }
        tableView.reloadData()
    }
    
    /// 檢測設備連接狀態
    private func checkConnectedPrinter() {
        connectedPrinters.removeAll()
        let printer = PTDispatcher.share()?.printerConnected
        if let printer = printer {
            connectedPrinters = [printer]
        }
        reloadData()
    }
    
    /// 掃描設備
    private func scanPrinters() {
        DispatchQueue.main.async {
            let scannedHeader = self.tableView.headerView(forSection: CellIndex.scanned.rawValue) as? PrinterConnectHeaderView
            self.isScanningWiFi = true
            scannedHeader?.startAnimating()
            PTDispatcher.share()?.scanWiFi({ [weak self] printers in
                guard let self = self else { return }
                self.isScanningWiFi = false
                scannedHeader?.stopAnimating()
                if let printers = printers as? [PTPrinter] {
                    self.scannedPrinters = printers
                    self.reloadData()
                }
            })
        }
    }
    
    /// 連接設備
    private func connectPrinter(_ printer: PTPrinter) {
        /// 連接成功的回調
        PTDispatcher.share().whenConnectSuccess { [weak self] in
            guard let self = self else { return }
            ProgressHUDManager.dismiss()
            
            /// 保存連接成功的設備
            if let connectedPrinter = PTDispatcher.share().printerConnected {
                UserDefaultsManager.setPrinter(connectedPrinter)
            }
            
            self.checkConnectedPrinter()
        }
        
        /// 連接失敗的回調
        PTDispatcher.share().whenConnectFailureWithErrorBlock { error in
            ProgressHUDManager.showError(message: "連接設備失敗")
        }
        
        /// 開始連接
        ProgressHUDManager.showLoading(message: "連接中，請稍等...")
        PTDispatcher.share().connect(printer)
    }
    
    /// 斷開設備
    private func disconnectPrinter() {
        PTDispatcher.share().disconnect()
    }

    // MARK: - Getter
    private lazy var tableView: UITableView = {
        let tv = UITableView(frame: view.bounds, style: .grouped)
        tv.delegate = self
        tv.dataSource = self
        tv.register(cellType: PrinterConnectTCell.self)
        tv.register(cellType: PrinterConnectSwitchTCell.self)
        tv.register(headerFooterViewType: PrinterConnectHeaderView.self)
        return tv
    }()
}

extension PrinterConnectViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch CellIndex(rawValue: section) {
        case .connected: return connectedPrinters.count + 1
        case .history: return historyPrinters.count
        case .scanned: return scannedPrinters.count
        default: return 0
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == CellIndex.connected.rawValue && indexPath.row == 0 {        /// 當前设备开关
            let cell = tableView.dequeueReusableCell(for: indexPath, cellType: PrinterConnectSwitchTCell.self)
            /// 斷開設備連接
            cell.disconnectBtnClick = { [weak self] in
                print("點擊了斷開按鈕")
                self?.disconnectPrinter()
            }
            /// 是否顯示"斷開"按鈕
            cell.disconnectBtnHidden = connectedPrinters.isEmpty
            return cell
        }
        let cell = tableView.dequeueReusableCell(for: indexPath, cellType: PrinterConnectTCell.self)
        if indexPath.section == CellIndex.connected.rawValue {         /// 當前設備
            let printer = connectedPrinters[indexPath.row - 1]
            cell.title = printer.ip + "[" + printer.name + "]"
        }
        if indexPath.section == CellIndex.history.rawValue {         /// 連結過的設備
            let printer = historyPrinters[indexPath.row]
            cell.title = printer.ip + "[" + printer.name + "]"
        }
        if indexPath.section == CellIndex.scanned.rawValue {         /// 其他設備
            let printer = scannedPrinters[indexPath.row]
            cell.title = printer.ip
        }
        return cell
    }
    
}


extension PrinterConnectViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == CellIndex.history.rawValue {
            let printer = historyPrinters[indexPath.row]
            connectPrinter(printer)
        }
        if indexPath.section == CellIndex.scanned.rawValue {
            let printer = scannedPrinters[indexPath.row]
            connectPrinter(printer)
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = tableView.dequeueReusableHeaderFooterView(PrinterConnectHeaderView.self)
        switch CellIndex(rawValue: section) {
        case .connected: headerView?.title = ""
        case .history: headerView?.title = "連結過的設備"
        case .scanned:
            headerView?.title = "其他設備"
            isScanningWiFi ? headerView?.startAnimating() : headerView?.stopAnimating()
        default: break
        }
        return headerView
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if historyPrinters.isEmpty && CellIndex.history.rawValue == section {
            return 0
        }
        return 30
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 30
    }
}
